//
//  ZYCMessageRootViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/15.
//

#import "ZYCMessageRootViewController.h"
#import "ZYCMessageRootCell.h"
#import "ZYCMessageRootModel.h"
#import "ZYCMessageTitleButton.h"
#import "ZYCNoDataView.h"
#import "ZYCNoticeCalendarDetailContentViewController.h"
#import "ZYCMessageDutyViewController.h"
#import "ZYCMessageRecordViewController.h"
#import "ZYCStuLeaveRecordDetailViewController.h"
#import "ZYCTeachingTeachLearningPaperViewController.h"
#import "ZYCTeachingTeachLearningDetailViewController.h"
#import "ZYCMessageAttendanceViewController.h"
#import "ZYCTeaLeaveRecordApproveViewController.h"
#import "ZYCTeaLeaveRecordSendDetailViewController.h"

static NSInteger pageSize = 10;
#define controlTime 30
@interface ZYCMessageRootViewController ()<UINavigationControllerDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) ZYCMessageTitleButton *messageButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, assign) NSInteger second;
@property (nonatomic, assign) NSInteger totalMsg;
@property (nonatomic, strong) ZYCNoDataView *noDataView;
@property (nonatomic, assign) BOOL isFile;

@property (nonatomic, assign) ZYCLoginRoleType roleType;
@end

@implementation ZYCMessageRootViewController

#pragma mark - 生命周期函数
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.second = controlTime;
    [self.view addSubview:self.messageButton];
    [self.messageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15.0f);
        make.top.equalTo(self.view).offset(kStatusBarHeight +7.5f);
    }];
    [self.view addSubview:self.tableView];
    
    self.isFile = YES;
    NSInteger roleType =  [[NSUserDefaults standardUserDefaults] integerForKey:@"kUserRoleType"];
      if (roleType == 0) {
          self.roleType = ZYCLoginRoleTypeTeacher;//教师
      }else{
          self.roleType = ZYCLoginRoleTypeParent;//家长
      }
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;

    [self loadNewData];
    self.second = controlTime;
    [self.timer setFireDate:[NSDate distantPast]];//开启定时器
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.timer setFireDate:[NSDate distantFuture]];//关闭定时器
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCMessageRootCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCMessageRootCell class]) forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.section];
    [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
    
    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 75.0;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

// 1：通知；2：周历；3：行政值班；4：学生请假；5：评价评学；6：巡堂记录
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ZYCMessageRootModel *model = self.dataSource[indexPath.section];
    if ([model.msgType integerValue] == 1) {//通知
        ZYCNoticeCalendarDetailContentViewController *vc = [ZYCNoticeCalendarDetailContentViewController new];
        vc.noticeId = model.parentId;
        vc.type = ZYCNoticeCalendarDetailContentTypeRcv;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([model.msgType integerValue] == 2){//周历
        ZYCNoticeCalendarDetailContentViewController *vc = [ZYCNoticeCalendarDetailContentViewController new];
        vc.noticeId = model.parentId;
        vc.type = ZYCNoticeCalendarDetailContentTypeRcv;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([model.msgType integerValue] == 3){//行政值班
        ZYCMessageDutyViewController *vc = [ZYCMessageDutyViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if([model.msgType integerValue] == 4){//学生请假
        ZYCStuLeaveRecordDetailViewController *vc = [ZYCStuLeaveRecordDetailViewController new];
        vc.titleString = model.msg;
        vc.leaveId = model.parentId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([model.msgType integerValue] == 5){//评价评学
        [self judgeTeachLearningStatus:model.parentId];
    }else if([model.msgType integerValue] == 6){//巡堂记录
        ZYCMessageRecordViewController *vc = [ZYCMessageRecordViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if([model.msgType integerValue] == 7){//考勤消息
        ZYCMessageAttendanceViewController *vc = [ZYCMessageAttendanceViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if([model.msgType integerValue] == 8){//审批消息
        [self checkTaskIsDone:model.parentId];
    }
}

- (void)checkTaskIsDone:(NSString *)teacherLeaveId{
    NSDictionary *params = @{
        @"teacherLeaveId":teacherLeaveId
    };
    [[URLManager sharedURLManager] postUrlString:Message_Post_CheckTaskIsDone requestService:RequestServiceActiviti parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                NSDictionary *dict = responseObject[@"body"];
                NSString *taskId = dict[@"taskId"];
                if ([dict[@"doneFlag"] integerValue] == 1) {//已审批
                    ZYCTeaLeaveRecordSendDetailViewController *vc = [[ZYCTeaLeaveRecordSendDetailViewController alloc] init];
                    vc.teacherLeaveId = teacherLeaveId;
                    vc.taskId = @"";
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    ZYCTeaLeaveRecordApproveViewController *vc = [ZYCTeaLeaveRecordApproveViewController new];
                    vc.teacherLeaveId = teacherLeaveId;
                    vc.taskId = taskId;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
    
}
// 判断评教评学状态
- (void)judgeTeachLearningStatus:(NSString *)quEvalutionId{
    NSDictionary *params = @{
        @"quEvalutionId":quEvalutionId
    };
    
    [[URLManager sharedURLManager] postUrlString:Message_Post_GetTeachLearningFlag requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            NSLog(@"值:%zd",[responseObject[@"body"] integerValue]);
            //（1：跳到详情页；0：跳到编辑页）
            if ([responseObject[@"body"] integerValue] == 1) {//已完成
                ZYCTeachingTeachLearningDetailViewController *vc = [ZYCTeachingTeachLearningDetailViewController new];
                vc.quEvalutionId = quEvalutionId;
                [self.navigationController pushViewController:vc animated:YES];
            }else{// 做题
                ZYCTeachingTeachLearningPaperViewController *vc = [ZYCTeachingTeachLearningPaperViewController new];
                vc.quEvalutionId = quEvalutionId;
                [self.navigationController pushViewController:vc animated:YES];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
//// 1：通知；2：周历；3：行政值班；4：学生请假；5：评价评学；6：巡堂记录
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCMessageRootModel *model = self.dataSource[indexPath.section];
    if([model.msgType integerValue] == 3 || [model.msgType integerValue] == 6){
        return UITableViewCellEditingStyleNone;
    }else{
        return UITableViewCellEditingStyleDelete;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCMessageRootModel *model = self.dataSource[indexPath.section];
    if([model.msgType integerValue] == 3 || [model.msgType integerValue] == 6){
        return NO;
    }else{
        return YES;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    ZYCMessageRootModel *model = self.dataSource[indexPath.section];
    [self deleteMessage:model];
}


    
#pragma mark - 定时器

// 开启定时器
- (void)startTimer{
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}


- (void)timerAction:(NSTimer *)timer{
    self.second -= 1;
    NSLog(@"%zd",self.second);
    if (self.second <= 0) {
        self.second = controlTime;
        [self.timer setFireDate:[NSDate distantPast]];//开启定时器
        [self.tableView.mj_header beginRefreshing];

    }
}

#pragma mark - getters
- (ZYCMessageTitleButton *)messageButton {
    if (!_messageButton) {
        _messageButton = [[ZYCMessageTitleButton alloc] initWithFrame:CGRectZero];
    }
    return _messageButton;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0]; 
    }
    return _dataSource;
}

- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight - kTabBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCMessageRootCell class] forCellReuseIdentifier:NSStringFromClass([ZYCMessageRootCell class])];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _tableView;
}

#pragma mark - 网络请求
//信息列表
- (void)loadNewData{
    self.pageNum = 1;
    NSDictionary *params = @{
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum)
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Message_Post_MessageList requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            [MrjSVProgressHUD dismiss];
            if (self.isFile) {
                // 开启定时器
                [self startTimer];
                self.isFile = NO;
            }else{
                self.second = controlTime;
                [self.timer setFireDate:[NSDate distantPast]];//开启定时器
            }
            NSDictionary *dict = responseObject[@"body"][@"msgList"];
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCMessageRootModel class] json:dict[@"list"]];
            self.totalMsg = [responseObject[@"body"][@"totalMsg"] integerValue];
            [[NSNotificationCenter defaultCenter] postNotificationName:ZYCUnRedMessageCountNotification object:self userInfo:@{@"totalCount":@(self.totalMsg)}];
            [self.dataSource removeAllObjects];
            NSMutableArray *filterArr = [NSMutableArray arrayWithCapacity:0];
            if (self.roleType == ZYCLoginRoleTypeParent) {
                for (ZYCMessageRootModel *m in array) {
                    if ([m.msgTypeName isEqualToString:@"通知"] || [m.msgTypeName isEqualToString:@"学生请假"] || [m.msgTypeName isEqualToString:@"评教评学"]) {
                        [filterArr addObject:m];
                    }
                }
                [self.dataSource addObjectsFromArray:filterArr];
            }else{
                [self.dataSource addObjectsFromArray:array];
            }
            [self.tableView reloadData];
            [self reset];
            [self.tableView.mj_header endRefreshing];
            if (self.dataSource.count == 0) {
                self.noDataView.hidden = NO;
                self.tableView.hidden = YES;
            }else{
                self.noDataView.hidden = YES;
                self.tableView.hidden = NO;
            }
        }else{
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}


- (void)loadMoreData{
    self.pageNum ++;
    NSDictionary *params = @{
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum)
    };

    [[URLManager sharedURLManager] postUrlString:Message_Post_MessageList requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            NSDictionary *dict = responseObject[@"body"][@"msgList"];
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCMessageRootModel class] json:dict[@"list"]];
            if (array.count == 0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                NSMutableArray *filterArr = [NSMutableArray arrayWithCapacity:0];
                if (self.roleType == ZYCLoginRoleTypeParent) {
                    for (ZYCMessageRootModel *m in array) {
                        if ([m.msgTypeName isEqualToString:@"通知"] || [m.msgTypeName isEqualToString:@"学生请假"] || [m.msgTypeName isEqualToString:@"评教评学"]) {
                            [filterArr addObject:m];
                        }
                    }
                    [self.dataSource addObjectsFromArray:filterArr];

                }else{
                    [self.dataSource addObjectsFromArray:array];
                }
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            }
        }else{
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}


- (void)deleteMessage:(ZYCMessageRootModel *)model{
    NSDictionary *params = @{
        @"appMsgId":model.appMsgId,
        @"userId":model.userId,
        @"msgType":model.msgType
    };
    [[URLManager sharedURLManager] postUrlString:Message_Post_MessageDelete requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            [self.dataSource removeObject:model];
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];

}


- (void)reset{
    [self.tableView.mj_footer setRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_footer resetNoMoreData];
}


#pragma mark - UINavigationControllerDelegate
-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:[viewController isKindOfClass:[self class]] animated:YES];
}


- (void)dealloc{
    self.navigationController.delegate = nil;
    self.timer = nil;
    [self.timer invalidate];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
